<template>
  <div class="app-container">
    <div class="filter-container" style="margin-top:0px;padding-bottom: 0px;">
      <div class="box1">
        <el-input v-model="queryPage.name" class="filter-item" placeholder="模板名称" style="width: 150px" clearable />

        <el-button class="filter-item" icon="el-icon-search" type="primary" @click="search()">
          查询
        </el-button>
      </div>
      <div class="box2">
        <el-button type="primary" icon="el-icon-circle-plus-outline" @click="handleAdd">新增</el-button>
        <el-button type="primary" icon="el-icon-download" @click="handleDownLoad">目录模板下载</el-button>
      </div>
    </div>

    <el-table v-loading="listLoading" :data="list" :height="tableHeight2" style="width: 100%;margin-top:10px; overflow:auto" border>
      <el-table-column label="序号" type="index" :index="indexMethod" header-align="center" align="center" width="80" />
      <el-table-column header-align="center" align="left" label="操作" width="400" fixed="right">
        <template slot-scope="scope">
          <el-button v-if="scope.row.state === '1'" type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button v-if="scope.row.state === '1'" type="primary" size="small" @click="addGroup(scope)">目录管理</el-button>
          <el-button v-if="scope.row.state === '1'" type="primary" size="small" @click="upGroup(scope)">目录导入</el-button>
          <el-button type="primary" size="small" @click="copy(scope)">复制</el-button>
          <el-button v-if="scope.row.state==='1' && scope.row.code === 'PROJECT_CATALOG'" type="danger" size="small" @click="updateStatus(scope, '2', '禁用')">禁用</el-button>
          <el-button v-if="scope.row.state==='2' && scope.row.code === 'PROJECT_CATALOG'" type="primary" size="small" @click="updateStatus(scope, '1', '启用')">启用</el-button>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="left" label="模板code" width="150" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ scope.row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="left" label="模板名称">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="left" label="备注">
        <template slot-scope="scope">
          <span>{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="left" label="状态" width="150">
        <template slot-scope="scope">
          <span>{{ getDicName(scope.row.state,'YW_BASE_STATUS') }}</span>
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="left" label="创建人" width="150">
        <template slot-scope="scope">
          {{ scope.row.createuserName }}
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="right" label="创建时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.createtimeTi }}
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>-1" :total="total" :page.sync="queryPage.page" :limit.sync="queryPage.limit" @pagination="loadList" />

    <el-dialog v-dialogDrag :close-on-click-modal="false" :visible.sync="xmAddVisible" append-to-body width="600px" title="新增模板信息">
      <xm-add v-if="xmAddVisible" ref="xmAdd" :visible.sync="xmAddVisible" />
    </el-dialog>

    <el-dialog v-dialogDrag :close-on-click-modal="false" :visible.sync="xmEditVisible" append-to-body width="600px" title="编辑模板信息">
      <xm-edit v-if="xmEditVisible" ref="xmEdit" :proid="code" :visible.sync="xmEditVisible" />
    </el-dialog>

    <el-dialog v-dialogDrag :visible.sync="uploadFilesVisible" width="1200px" :close-on-click-modal="false" append-to-body title="目录管理">
      <upload-files v-if="uploadFilesVisible" ref="uploadFiles" style="height:540px" :proid="code" :visible.sync="uploadFilesVisible" />
    </el-dialog>

    <el-dialog v-dialogDrag :visible.sync="xmCopyVisible" width="600px" :close-on-click-modal="false" append-to-body title="模板复制">
      <xmCopy v-if="xmCopyVisible" ref="xmCopy" :proid="code" :visible.sync="xmCopyVisible" />
    </el-dialog>

    <el-dialog title="文件上传" width="600px" :visible.sync="dialogVisible">
      <div class="filter-container" style="text-align: center;">
        <el-upload
          ref="upload"
          name="uploadfile_ant"
          class="upload-demo"
          style="margin-top:10px;"
          drag
          multiple
          :limit="1"
          :action="uploadpath"
          :headers="uoloadheaders"
          accept=".xlsx, .xls"
          :on-change="handleChange"
          :on-remove="handleRemove"
          :on-exceed="handleExceed"
          :on-success="handleAvatarSuccess"
          :file-list="fileList"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <div slot="tip" class="el-upload__tip">只能上传xlsx/xls文件</div>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { getPage, updateState, downloadTemplate } from '@/api/catalogManage'
import { getDictListByCode } from '@/api/dict'
import { Message, MessageBox } from 'element-ui'
import { tableHeight2 } from '@/utils/tableHeight'
import { getToken } from '@/utils/auth'

import Pagination from '@/components/Pagination'

import XmAdd from '../catalogmanage/add' // eslint-disable-line no-unused-vars
import XmEdit from '../catalogmanage/edit' // eslint-disable-line no-unused-vars
import UploadFiles from '../catalogmanage/addGroup' // eslint-disable-line no-unused-vars
import xmCopy from '../catalogmanage/copy' // eslint-disable-line no-unused-vars

export default {
  components: { Pagination, XmAdd, XmEdit, UploadFiles, xmCopy },
  mixins: [tableHeight2],
  provide() {
    return {
      getList: this.loadList
    }
  },
  data() {
    return {
      listLoading: false,
      xmAddVisible: false,
      xmEditVisible: false,
      uploadFilesVisible: false,
      xmCopyVisible: false,
      queryPage: {
        page: 1,
        limit: 20,
        loginName: '',
        userName: null,
        state: null,
        beginDate: null,
        endDate: null
      },
      uploadpath: '',
      dialogImageUrl: '',
      downloadPath: '',
      uoloadheaders: {},
      fileList: [], // upload多文件数组
      dialogVisible: false,
      total: 0,
      list: [],
      xmStatus: []
    }
  },
  created() {
    this.getDictList('YW_BASE_STATUS')
    this.loadList()
  },
  methods: {
    indexMethod(index) {
      return (index + 1) + (this.queryPage.page - 1) * this.queryPage.limit
    },
    getDictList(code) {
      getDictListByCode(code).then(response => {
        if (code === 'YW_BASE_STATUS') {
          this.xmStatus = response.data
        }
      })
    },
    getDicName(code, flag) {
      var dict = []
      if (flag === 'YW_BASE_STATUS') {
        dict = this.xmStatus
      }
      for (var i in dict) {
        if (dict[i].code === code) {
          return dict[i].name
        }
      }
    },
    search() { // 查询
      this.loadList()
    },
    loadList() { // 加载列表
      this.list = []
      this.listLoading = true
      getPage(this.queryPage).then(response => {
        const { data } = response
        this.list = data.records

        this.total = parseInt(data.total)
        this.listLoading = false
      }).catch(response => {
        this.listLoading = false
      })
    },
    handleAdd() {
      this.xmAddVisible = true
      this.$nextTick(() => {
        this.$refs.xmAdd
      })
    },
    handleEdit(scope) {
      this.xmEditVisible = true
      this.code = scope.row.id
      this.$nextTick(() => {
        this.$refs.xmEdit
        this.$refs.xmEdit.getDetailed()
      })
    },
    addGroup(scope) {
      this.uploadFilesVisible = true
      this.code = scope.row.id
      this.$nextTick(() => {
        this.$refs.uploadFiles
        this.$refs.uploadFiles.getDetailed()
      })
    },
    copy(scope) {
      this.xmCopyVisible = true
      this.code = scope.row.id
      this.$nextTick(() => {
        this.$refs.xmCopy
        this.$refs.xmCopy.getDetailed()
      })
    },
    updateStatus(scope, flag, type) {
      MessageBox.confirm('确认' + type, '确定', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: type + '中...',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.1)'
        })

        updateState({ code: scope.row.id, status: flag }).then(response => {
          Message({
            message: type + '成功',
            type: 'success',
            duration: 5 * 1000
          })
          // 重新加载表格
          this.loadList()
          loading.close()
        }).catch(response => {
          this.loadList()
          loading.close()
        })
      })
    },
    handleDownLoad() { // 下载模板
      downloadTemplate().then(response => {
        const blob = new Blob([response.data], {
          type: `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` // word文档为msword,pdf文档为pdf
        })
        const objectUrl = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = objectUrl
        link.setAttribute('download', '目录模板')
        document.body.appendChild(link)
        link.click()
        // 释放内存
        window.URL.revokeObjectURL(link.href)
      })
    },
    upGroup(scope) { // 上传
      this.dialogVisible = true
      this.fileList = []
      this.getUploadpath(scope.row.id)
    },
    getUploadpath(classifyId) {
      var path = '/catalogManage/uploadFile?classifyId=' + classifyId
      this.uploadpath = process.env.VUE_APP_BASE_API + path
      this.uoloadheaders = { 'X-Token': getToken() }
    },
    // 选取文件超过数量提示
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    // 移除
    handleRemove(file, fileList) {
      this.fileList = fileList
      // return this.$confirm(`确定移除 ${ file.name }？`);
    },
    // 监控上传文件列表
    handleChange(file, fileList) {
      const existFile = fileList.slice(0, fileList.length - 1).find(f => f.name === file.name)
      if (existFile) {
        this.$message.error('当前文件已经存在!')
        fileList.pop()
      }
      this.fileList = fileList
    },
    handleAvatarSuccess(res, file) {
      this.uploadLoading = false
      if (res.code === 20000) {
        Message({
          message: '上传成功',
          type: 'success',
          duration: 5 * 1000
        })
        this.dialogVisible = false
        this.loadList()
      } else {
        Message({
          message: res.msg,
          type: 'error',
          duration: 5 * 1000
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.app-container{
  padding:10px 20px;
}
.filter-container {
  padding-bottom: 10px;

  .filter-item {
    display: inline-block;
    vertical-align: middle;
    margin-bottom: 10px;
    margin-right: 10px;
  }
  .date-filter-item{
    vertical-align: middle;
    margin-bottom: 10px;
    margin-right: 10px;
  }
  .box1 {
    flex: 1;
    vertical-align: middle;
    float: inline-start;
  }
  .box2 {
    flex: 1;
    text-align: end;
    float: inline-end;
  }
}
.pagination-container {
  margin-top: 0 !important;
  padding: 10px 16px !important;
}
</style>
